package sms

import (
	"crypto/md5"
	"encoding/hex"
	oldjson "encoding/json"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/httpclient"
	"net/http"
	"sort"
	"strings"
)

func encryptUtilMD5(input map[string]string) (string, []string) {
	data := ""
	var key []string
	for k, _ := range input {
		key = append(key, k)
	}
	sort.Strings(key)
	for _, k := range key {
		data += k + input[k]
	}
	hash := md5.Sum([]byte(data))
	return strings.ToUpper(hex.EncodeToString(hash[:])), key
}
func DianxinsendSms(Url, userName, password, destNum, srcNum, timestamp, addSerial, signatureId, templateId, param string) (map[string]interface{}, error) {
	params := make(map[string]string)
	params["cust_code"] = userName
	params["password"] = password
	params["sp_code"] = srcNum
	params["templateId"] = templateId
	params["timestamp"] = timestamp
	params["destMobiles"] = destNum
	params["params"] = param
	if addSerial != "" {
		params["addSerial"] = addSerial
	}
	if signatureId != "" {
		params["signature_id"] = signatureId
	}
	apiKey, paramsKey := encryptUtilMD5(params) // Assuming you have a function named encryptUtilMD5 that computes the MD5 hash
	var (
		req     http.Request
		bodyStr string
		err     error
		//res     *http.Response
	)
	req.ParseForm()
	req.Form.Add("sign", apiKey)
	for _, k := range paramsKey {
		if k != "password" {
			req.Form.Add(k, params[k])
		}
	}
	bodyStr = strings.TrimSpace(req.Form.Encode())
	//if res, err = http.Post(Url, "application/x-www-form-urlencoded", strings.NewReader(bodyStr)); err != nil {
	//	return nil, err
	//}
	//defer res.Body.Close()
	//resTokenByte, err := ioutil.ReadAll(res.Body)
	//if err != nil {
	//	return nil, nil
	//}
	header := make(http.Header)
	header.Set("Content-Type", "application/x-www-form-urlencoded")
	var resBody []byte
	if resBody, _, err = httpclient.PublicRequireByPost(Url, header, []byte(bodyStr)); err != nil {
		return nil, err
	}
	resToken := make(map[string]interface{})
	if err = oldjson.Unmarshal(resBody, &resToken); err != nil {
		return nil, err
	}
	return resToken, nil
}
